package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"note-xmgr/cache"
	"note-xmgr/model"
	"strconv"
	"time"
)

func AddRedBook(c *gin.Context) {
	name := c.PostForm("name")
	comment := c.PostForm("comment")
	author := c.PostForm("author")
	if name == "" || comment == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.RedBook{
		Name:    name,
		Comment: comment,
		Author:  author,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	var red_book model.RedBook
	redis_key := "add_red_book" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Debug().Find(&red_book)
	jsonData, _ := json.Marshal(red_book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func RedBookDetail(c *gin.Context) {
	id := c.Query("id")
	var red_book model.RedBook
	err := model.DB.Where("id=?", id).First(&red_book).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询详情成功",
		"data": red_book,
	})
	return
}

func RedBookDelete(c *gin.Context) {
	id := c.Query("id")
	var red_book model.RedBook
	err := model.DB.Where("id=?", id).Delete(&red_book).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "red_book_delete" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func RedBookList(c *gin.Context) {
	var red_book []model.RedBook
	err := model.DB.Find(&red_book).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表展示失败",
		})
		return
	}
	redis_key := "red_book_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&red_book)
		jsonData, _ := json.Marshal(red_book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &red_book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": red_book,
	})
	return

}
